/**
 * 用canvas截取图片中的人脸
 * @param {Object} params
 * @param {string} params.originSrc 原图地址
 * @param {Object} params.imageInfo 原图信息
 * @param {Array} params.itemList 人脸信息数组
 * @returns {Promise<Array>} 返回人脸图片地址
 */
export const getFaceAvatar = ({ originSrc, imageInfo, itemList }) => {
  const { width: originWidth, height: originHeight } = imageInfo;

  const promises = itemList.map(async item => {
    const { x, y, width: w, height: h } = item;

    const width = w * originWidth;
    const height = h * originHeight;
    const X = x * originWidth;
    const Y = y * originHeight;

    return new Promise(resolve => {
      const backgroundImage = new Image();
      backgroundImage.src = originSrc;

      backgroundImage.onload = function () {
        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        canvas.width = width;
        canvas.height = height;
        context.drawImage(backgroundImage, X, Y, width, height, 0, 0, width, height);
        // context.drawImage(backgroundImage, X, Y, width, height, 0, 0, originWidth, originHeight);
        const dataURL = canvas.toDataURL("image/png");
        item.avatarSrc = dataURL;
        resolve(item);
      };

      backgroundImage.onerror = function () {
        resolve(item);
      };
    });
  });

  return Promise.all(promises);
};

/**
 * 用backgroundPosition定位图片中的人脸
 * @param {Object} params
 * @param {string} params.originSrc 原图地址
 * @param {Array} params.itemList 人脸信息数组
 * @returns {Promise<Array>} 返回人脸图片地址
 */
export const getFaceAvatarByPosition = ({ originSrc, itemList }) => {
  const promises = itemList.map(async item => {
    const { x, y, width: w, height: h } = item;

    return new Promise(resolve => {
      const backgroundImage = new Image();
      backgroundImage.src = originSrc;

      backgroundImage.onload = function () {
        const { width, height } = backgroundImage;
        const avatarInfo = {
          width: width * w,
          height: height * h,
          src: originSrc,
          posX: width * x,
          posY: height * y
        };
        item.avatarInfo = avatarInfo;
        resolve(item);
      };

      backgroundImage.onerror = function () {
        resolve(item);
      };
    });
  });

  return Promise.all(promises);
};
